package org.kojo.tdrm.servlet;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;
import org.json.JSONObject;
import org.kojo.tdrm.entity.User;
import org.kojo.tdrm.model.MyError;
import org.kojo.tdrm.service.UserAppService;
import org.kojo.tdrm.utils.App;
import org.kojo.tdrm.utils.HttpUtils;

public class FBConnect extends HttpServlet {
	//
	private static Logger log = Logger.getLogger(FBConnect.class.getName());
	String appId = App.APPID;
	String appSecret = App.APPSECRET;
	String url = App.BASE_DOMAIN+"/fbconnect";
	

	public void processRequest(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String graphUrl = "https://graph.facebook.com/me?access_token=";
		UserAppService service = new UserAppService();
		HttpUtils httpUtil = new HttpUtils();
		//String testUser = null;
		//testUser = this.getInitParameter("TESTUSER");
		String usertest = null;
		usertest = req.getParameter("usertest");
		log.fine("Check if User test is exist testuser= "+usertest);
		if(usertest!=null){
			req.getSession().setAttribute(App.USERID, usertest);
			service.updateUser(new User(usertest, new Date()));
			resp.sendRedirect("/restricted/main.jsp");
			//req.getRequestDispatcher("/").forward(req, resp);
			return;
		}
		String code = req.getParameter("code");
		log.fine("code param=" + code);
		
		if (code != null || "".equals(code)) {
			//String currentToken = (String)req.getSession(false).getAttribute(App.FBTOKEN);
			String tokenUrl = "";
			//if(currentToken==null){
			tokenUrl = "https://graph.facebook.com/oauth/access_token?"
					+ "client_id=" + appId + "&redirect_uri=" + url + "&"
					+ "client_secret=" + appSecret + "&code=" + code;
			/*} else {
				String extendTokenUrl = "https://graph.facebook.com/oauth/access_token?client_id="+appId+"&client_secret="+appSecret+"&grant_type=fb_exchange_token&fb_exchange_token="+currentToken;
				tokenUrl = extendTokenUrl;
			}*/
			String content = httpUtil.getUrlContent(tokenUrl);
			log.fine("tokenQuery=" + content);
			String token = httpUtil.getQueryMap(content).get("access_token");
			log.fine("token=" + token);
			graphUrl += token;
			String graphContent = httpUtil.getUrlContent(graphUrl);
			log.fine("graphContent=" + graphContent);
			try {
				JSONObject graph = new JSONObject(graphContent);
				MyError error = this.parseError(graph);
				if(error.isError()){
					throw new ServletException("FB Connection error-> "+error.toString());
				}
				String profileId = (String)graph.get("id");
				String email = (String) graph.get("email");
				log.fine("useremail=" + email);
				User u = service.findUser(email);
				if (u == null) {
					service.createUser(new User(email,profileId,new Date()));
				} else {
					service.updateUser(new User(email,profileId,new Date()));
				}
				req.getSession().setAttribute(App.USERID, email);
				req.getSession().setAttribute(App.FBTOKEN, token);
				req.getSession().setAttribute(App.FB_PROFILEID, profileId);
			} catch (JSONException e) {
				throw new ServletException(e);
			} catch (Exception e) {
				throw new ServletException(e);
			}

		}
		//goto welcome page after login
		//req.getRequestDispatcher("/").forward(req, resp);
		resp.sendRedirect("/restricted/main.jsp");
	}

	public MyError parseError(JSONObject graph) {
		MyError me = new MyError();
		//{"error":{"message":"Error validating application. Invalid application ID.","type":"OAuthException","code":190}}
		try {
			
			JSONObject o = (JSONObject) graph.get("error");
			String msg = o.getString("message");
			String type = o.getString("type");
			String code = o.getString("code");
			me.setMessage(msg);
			me.setType(type);
			me.setCode(Integer.parseInt(code));
			me.setError(true);
		} catch (JSONException e) {
			//e.printStackTrace();
		}
		return me;
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		processRequest(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		processRequest(req, resp);
	}

	

	

}